package org.example.acl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.domain.PrincipalSid;
import org.springframework.security.acls.model.MutableAcl;
import org.springframework.security.acls.model.MutableAclService;
import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.Sid;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SecureAppInitializer implements InitializingBean {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private MutableAclService aclService;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("initialize users...");
        User user = userRepository.getById(1);
        log.info("user: {}", user);
        ObjectIdentity oid = new ObjectIdentityImpl("user", user.getId());
        log.info("oid: {}", oid);

        Sid sid = new PrincipalSid("user:" + user.getId());

        MutableAcl acl = aclService.createAcl(oid);
        acl.insertAce(0, BasePermission.READ, sid, true);
        log.info("access control entries:");
        for (var ace : acl.getEntries()) {
            log.info(" * {}", ace);
        }

    }
}
